if (window != window.top) window.top.location.href = window.location.href;  //使本系统始终在顶级窗口中打开,不允许被iframe包含
var tabTitles = {};
//在主界面上添加新的tab
function AddTab(title, url, closable, iconCls) {
    if (typeof (closable) == 'undefined') closable = true;
    if (tabTitles[title]) {
        title += ' [' + tabTitles[title]++ + ']';
    }
    else tabTitles[title] = 1;
    $('#tab').tabs('add',
       {
           title: title, closable: closable,
           content: '<iframe src="' + url + '" scrolling="auto" frameborder="0" width="100%" height="100%"></iframe>',
           style: { overflow: 'hidden' },
           iconCls: iconCls
       }
    );
}

//刷新当前页面
function ReloadCurrentPage() {
    var selected = $('#tab').tabs('getSelected');
    if (selected) {
        var lastframe = null;
        var iframe = selected.find('iframe');
        while (iframe.length > 0) {
            lastframe = iframe[0];
            try{
               iframe = $(lastframe.contentDocument.body).find('.show_fullscreen_dialog');
            }catch(e){break;}
        }
        lastframe.contentWindow.location.reload(true);
    }
}

function CloseCurentPage() {
    var selected = $('#tab').tabs('getSelected');
    var index = $('#tab').tabs('getTabIndex', selected);
    $('#tab').tabs("close", index);
}

//关闭所有页面
function CloseAllTable() {
    $.messager.confirm('确认', '确实要关闭所有可关闭页面？', function (r) {
        if (r) {
            var tabs = $('#tab').tabs("tabs");
            for (var i = tabs.length - 1; i >= 0; i--) {
                var onetab = tabs[i].panel('options');
                if (onetab.closable) {
                    $('#tab').tabs("close", i);
                }
            }
        }
    });
}

//在新窗口中打开当前页
function OpenPageInNewWindow() {
    var selected = $('#tab').tabs('getSelected');
    if (selected) {
        var lastframe = null;
        var iframe = selected.find('iframe');
        while (iframe.length > 0) {
            lastframe = iframe[0];
            try {
                iframe = $(lastframe.contentDocument.body).find('.show_fullscreen_dialog');
            } catch (e) { break; }
        }
        var href = lastframe.contentWindow.location.href;
        Href(href, true);
    }
}

function ChangeWebSite(websiteCode, title) {
    $('#menu').tree({ url: serverUrl.webRoot + 'Home/Menutree?WebSiteCode=' + websiteCode });
    $('.home').layout('panel', 'west').panel('setTitle', title);
}

function menuItemClick(node) {
    if (node.attributes && node.attributes.url && node.attributes.url != '') {
        AddTab(node.text, node.attributes.url, true, node.iconCls);
    }
    else {
        if (node.state == 'open')
            $('#menu').tree('collapse', node.target);
        else
            $('#menu').tree('expand', node.target);
    }
}

function reloadManagerList() {
    var iframe = ChatManagerListWindow.find('iframe')[0];
    iframe.contentWindow.location.reload(true);
}

function chgpwd(url) {
    var win = showWindow({
        title: '修改密码',
        width: 450,
        height: 220,
        iconCls:'icon-key',
        content: '<iframe src="' + url + '",scrolling="auto" width="100%" height="100%" frameborder="0")"></iframe>'
                , minimizable: false
                , collapsible: false
                , maximizable: false
                , resizable: false
    })
    win.find('iframe')[0].close = function () {
        win.window('close');
    };
}

function chgdata(url) {
    var win = showWindow({
        title: '个人资料',
        width: 480,
        height: 300,
        iconCls: 'icon201304231544461154',
        content: '<iframe src="' + url + '",scrolling="auto" width="100%" height="100%" frameborder="0")"></iframe>'
                , minimizable: false
                , collapsible: false
                , maximizable: false
                , resizable: false
    })
    win.find('iframe')[0].close = function () {
        win.window('close');
    };
}



//开始=====================即时通讯========================================

var sendWindows = {};  //所有的聊天窗口
var chatMessage = [];   //消息
var mainWinMsg;
var ChatManagerListWindow = null;

$(document).ready(function () {
    if (ChatView) {
        mainWinMsg = $('.chat_content>.easyui-linkbutton');

        chatMessage = loadMessageFromCookies();
        showchatMessage();
        Received();

        mainWinMsg.click(function () {
            if (mainWinMsg.IntervalID != undefined) {
                for (var i = 0; i < chatMessage.length; i++) {
                    if (sendWindows[chatMessage[i].SendUserName] == undefined) {
                        openSendWind(chatMessage[i].SendUserName, chatMessage[i].SendRealName + ' (' + chatMessage[i].SendUserName + ')', showchatMessage);
                    }
                }
                return false;
            }
        });
    }
});

function ShowManagerList(url) {
    if (ChatManagerListWindow == null) {
        ChatManagerListWindow = $('<div/>').window({
            title: '用户列表',
            iconCls: 'icon-chat',
            width: 200,
            height: 300,
            left: -200,
            top: -300,
            content: '<iframe style="width:100%;height:100%;" src="' + url + '" scrolling="auto" frameborder="0"></iframe>',
            collapsible: false,
            minimizable: false,
            closable: true,
            tools: [{ iconCls: 'icon-reload', handler: reloadManagerList}],
            onBeforeClose: function () {
                ChatManagerListWindow.window('minimize');
                return false;
            }
        });
        $(window).resize(function () {
            var options = ChatManagerListWindow.window('options');
            if (options.minimized == false && options.closed == false) {
                ChatManagerListWindow.window('resize', {
                    left: $(window).width() - options.width - 5,
                    top: $(window).height() - options.height - $('.footer').outerHeight() - 10
                });
            }
        });
        ChatManagerListWindow.resize();
    }
    else {
        ChatManagerListWindow.window('open').resize();
    }
}

//从服务器接收数据
function Received() {
    $.ajax(serverUrl.webRoot + 'ChatReceived',
         {
             data: {},
             type: 'POST',
             complete: function (data) {
                 var json = parseJSON(data.responseText);
                 if (json != undefined) {
                     if ($.isArray(json)) {
                         for (var i = 0; i < json.length; i++) {
                             var j;
                             for (j = 0; j < chatMessage.length; j++) {
                                 if (json[i].ID == chatMessage[j].ID) {
                                     break;
                                 }
                             }
                             if (j >= chatMessage.length) {
                                 chatMessage.push(json[i]);
                             }
                         }
                         showchatMessage();
                         Received();
                     }
                 }
                 else {
                     Received();
                 }
             }
         });
}

//显示数据到聊天窗口
function showchatMessage() {
    if (chatMessage.length > 0) {
        for (var j = 0; j < chatMessage.length; j++) {
            for (var userName in sendWindows) {
                var win = sendWindows[userName];
                if (win == undefined) break;
                if (userName == chatMessage[j].SendUserName) {
                    var iframes = win.find('iframe');
                    if (iframes.length > 0) {
                        var iframe = iframes[0];
                        if (iframe && iframe.received) {
                            iframe.received(chatMessage[j]);
                            array.RemoveAt(chatMessage, j--);
                            break;
                        }
                    }
                }
            }
        }
        if (chatMessage.length > 0) {
            if (mainWinMsg.IntervalID == undefined) {
                var isshow = true;
                mainWinMsg.IntervalID = setInterval(function () {
                    isshow = !isshow;
                    if (isshow) mainWinMsg.linkbutton({ text: '　　' });
                    else mainWinMsg.linkbutton({ text: '消息(' + chatMessage.length + ')' });
                }, 500);
            }
        }
        else {
            clearInterval(mainWinMsg.IntervalID);
            mainWinMsg.IntervalID = undefined;
            mainWinMsg.linkbutton({ text: '消息' });
        }
        saveMessageToCookies();
    }
}

function openSendWind(userName, realName,callbak) {
    if (sendWindows[userName] == undefined) {
        var url =  serverUrl.webRoot + 'Chat/Send?ReceivedUserName=' + userName;
        sendWindows[userName] = showWindow({
            iconCls: 'icon-chat',
            title: realName,
            width: 450,
            height: 500,
            minimizable: false,
            content: '<iframe src="' + url + '" scrolling="auto" frameborder="0" width="100%" height="100%"></iframe>',
            onClose: function () {
                sendWindows[userName] = undefined;
            }
        });
        var iframe = sendWindows[userName].find('iframe')[0];
        iframe.close = function () { sendWindows[userName].window('close'); };
        iframe.easyuiWindow = sendWindows[userName];
        $(iframe).load(callbak);
    }
    else {
        sendWindows[userName].window('center').window('open');
    }
}

function loadMessageFromCookies() {
    var msg = Cookies('ChatMessage');
    if (msg == undefined || msg == '') msg = [];
    else msg = JSON.parse(msg);
    return msg;
}

function saveMessageToCookies() {
    Cookies('ChatMessage', JSON.stringify(chatMessage), { path: serverUrl.webRoot + 'Home/Index', expires: '10000/01/01' });
}

//结束=====================即时通讯========================================
